<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="7">
          <!-- clear清空查询内容并重载 -->
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="handleAddUser">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区 -->
      <el-table :data="userlist" style="width: 100%" stripe="" border>
        <el-table-column type="index"></el-table-column>
        <el-table-column
          prop="username"
          label="姓名"
          width="180"
        ></el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column label="状态">
          <!-- 作用域插槽 -->
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <!-- 操作区 -->

        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="handleAlterVisible(scope.row.id)"
            ></el-button>
            <!-- 删除改按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteById(scope.row.id)"
            ></el-button>
            <!-- 分配角色 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="showSetRoleDialogVisible(scope.row)"
              ></el-button
            ></el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 3, 5]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户表单区 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addUserVisible"
      @close="addDialogClosed"
      :close-on-click-modal="false"
    >
      <el-form
        :model="addForm"
        label-width="70px"
        :rules="addFormRules"
        ref="addFormRef"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="addForm.username"
            placeholder="请输入内容"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="addForm.password"
            placeholder="请输入内容"
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email" placeholder="请输入内容"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input
            v-model="addForm.mobile"
            placeholder="请输入内容"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleAddUser">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 修改用户信息区 -->
    <el-dialog
      title="修改用户信息"
      :visible.sync="alterDialogVisible"
      :close-on-click-modal="false"
      @close="alterDialogClosed"
    >
      <el-form
        :model="alterForm"
        :rules="alterFormRules"
        ref="alterFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="alterForm.username" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="alterForm.mobile"></el-input> </el-form-item
        ><el-form-item label="邮箱" prop="email">
          <el-input v-model="alterForm.email"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="alterDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleAlter">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog
  title="分配角色"
  :visible.sync="setRoleDialogVisible"
  width="30%" 
  >
  <p>当前的用户：{{currentUser.username}}</p>
  <p>当前的角色：{{currentUser.role_name}}</p>
  <span>分配新角色：</span>
   <el-select v-model="selectedId" placeholder="请选择">
    <el-option
      v-for="item in roleList"
      :key="item.id"
      :label="item.roleName"
      :value="item.id">
    </el-option>
  </el-select>
  <span slot="footer" class="dialog-footer">
    <el-button @click="setRoleDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="setRole(currentUser.id,selectedId)">确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>
<style scoped>

.el-pagination {
  margin-top: 15px;
}
</style>

<script>
export default {
  data() {
    //验证邮箱的规则
    var checkMail = (rule, value, cb) => {
      const regMail = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
      if (regMail.test(value)) {
        //合法的邮箱
        return cb()
      }
      cb(new Error('请输入合法的邮箱!'))
    }
    //验证手机号码的规则
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^1[345678]\d{9}$/
      if (regMobile.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的手机号码!'))
    }

    return {
      //获取用户列表的参数对象
      queryInfo: {
        query: '', //搜索关键字
        pagenum: 1,
        pagesize: 5,
      },
      userlist: [],
      total: 0,
      addUserVisible: false, //添加用户框显示状态
      alterDialogVisible: false, //编辑框显示状态
      setRoleDialogVisible: false,//分配角色对话框显示状态
      currentUser:{},//当前用户数据
      roleList:[],//所有角色数据
      selectedId:'',
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: '',
      },
      alterForm: {
        username: '',
        email: '',
        mobile: '',
        id: '',
      },
      addFormRules: {
        username: [
          {
            required: true,
            message: '请输入用户名',
            trigger: 'blur',
          },
          { min: 3, max: 10, message: '长度在3-10个字符之间', trigger: 'blur' },
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur',
          },
          { min: 6, max: 15, message: '长度在6-15个字符之间', trigger: 'blur' },
        ],
        email: [
          {
            required: true,
            message: '请输入邮箱',
            trigger: 'blur',
          },
          { validator: checkMail, trigger: 'blur' },
        ],
        mobile: [
          {
            required: true,
            message: '请输入手机号码',
            trigger: 'blur',
          },
          { validator: checkMobile, trigger: 'blur' },
        ],
      },
      alterFormRules: {
        email: [
          {
            required: true,
            message: '请输入邮箱',
            trigger: 'blur',
          },
          { validator: checkMail, trigger: 'blur' },
        ],
        mobile: [
          {
            required: true,
            message: '请输入手机号码',
            trigger: 'blur',
          },
          { validator: checkMobile, trigger: 'blur' },
        ],
      },
    }
  },

  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo,
      })
      if (res.meta.status !== 200) {
        return this.$message.error('用户列表获取失败!')
      }
      this.userlist = res.data.users
      this.total = res.data.total
    },
    //监听pagesize改变
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    //监听页码值改变
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    //监听用户状态改变
    async userStateChange(userinfo) {
      const { data: res } = await this.$http.put(
        'users/' + userinfo.id + '/state/' + userinfo.mg_state
      )
      if (res.meta.status != 200) {
        userinfo.mg_state = !userinfo.mg_state
        return this.$message.error('用户状态更新失败!')
      }
      this.$message.success('用户状态更新成功!')
    },
    //监听用户添加列表显示状态
    handleAddUser() {
      this.addUserVisible = !this.addUserVisible
    },
    //监听用户添加对话框重置
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    //添加用户请求
    async addUser() {
      //表单预校验
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) {
          return
        }
        const { data: res } = await this.$http.post('users', this.addForm)
        if (res.meta.status != 201) {
          return this.$message.error(res.meta.msg)
        }
        this.addUserVisible = false
        this.getUserList()
        this.$message.success('新用户添加成功')
      })
    },
    //监听修改信息框显示状态
    async handleAlterVisible(id) {
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status != 200) {
        return this.$message.error('查询失败')
      }
      this.alterForm = res.data
      this.alterDialogVisible = !this.alterDialogVisible
    },

    //监听修改信息框关闭重置
    alterDialogClosed() {
      this.$refs.alterFormRef.resetFields()
    },
    //保存修改信息
    handleAlter() {
      //预校验
      this.$refs.alterFormRef.validate(async (valid) => {
        if (!valid) {
          return
        }
        const { data: res } = await this.$http.put(
          'users/' + this.alterForm.id,
          this.alterForm
        )
        if (res.meta.status != 200) {
          return this.$message.error('保存失败')
        }
        this.$message.success('保存成功')
        this.alterDialogVisible = !this.alterDialogVisible
        this.getUserList()
      })
    },
    //根据id弹出删除确认框
    deleteById(id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          const { data: res } = await this.$http.delete('users/' + id)
          if (res.meta.status != 200) {
            return this.$message.error('删除失败!')
          }
          this.$message({
            type: 'success',
            message: '删除成功!',
          })
          this.getUserList()
        })
        .catch(() => {//该api取消实际上返回的是错误信息
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    //显示分配角色对话框
    async showSetRoleDialogVisible(userinfo){
      //获取所有角色数据
      const{data:res} = await this.$http.get('roles')
      if (res.meta.status!==200) {
        this.$message.error('获取角色数据失败')
      }
      this.roleList=res.data
      this.setRoleDialogVisible = true
      this.currentUser = userinfo
      
    },
    async setRole(userId,roleId){
      const{data:res} = await this.$http.put(`users/${userId}/role`, {rid:roleId})
      if (res.meta.status!==200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success('分配角色成功!')
      this.setRoleDialogVisible = false
      this.getUserList()
            }
  },
}
</script>